const express=require('express')
const mysql=require('mysql')
const database=require('../database')
// 实例化服务器对象
const goods=express.Router()
goods.use(express.urlencoded({extended:false}))
goods.use(express.json())
const db=mysql.createPool(database)
// 查询商品信息列表
goods.post('/list',(req,res)=>{
    let sql='select * from t_goods'
    db.query(sql,[],(err,list)=>{
        if(err){
            res.send({
                success:false,
                msg:'失败'
            })
        }else{
            res.send({
                success:true,
                msg:'成功',
                list
            })
        }
    })
})
// 查询商品详情
goods.post('/getGoods',(req,res)=>{
    let sql='select * from t_goods where id=?'
    db.query(sql,[req.body.id],(err,result)=>{
        if(result.length){
            res.send({
                success:true,
                msg:'成功',
                goods:result[0]
            })
        }else{
            res.send(err)
        }
    })
})
// 删除商品
goods.post('/deleteGoods',(req,res)=>{
    let sql='delete from t_goods where id=?'
    db.query(sql,[req.body.id],(err,result)=>{
        if(result.affectedRows){
            res.send({
                success:true,
                msg:'成功'
            })
        }else{
            res.send({
                success:false,
                msg:'失败'
            })
        }
    })
})
// 添加商品
goods.post('/addGoods',(req,res)=>{
    let sql='insert into t_goods(title,content,imagePath,price) values (?,?,?,?)'
    db.query(sql,[req.body.title,req.body.content,req.body.imagePath,req.body.price],(err,result)=>{
        if(result.insertId){
            res.send({
                success:true,
                msg:'成功'
            })
        }else{
            res.send({
                success:false,
                msg:'失败'
            })
        }
    })
})
// 修改商品
goods.post('/updateGoods',(req,res)=>{
    let sql='update t_goods set title=?,content=?,imagePath=?,price=? where id=?'
    db.query(sql,[req.body.title,req.body.content,req.body.imagePath,req.body.price,req.body.id],(err,result)=>{
        if(result.changedRows){
            res.send({
                success:true,
                msg:'成功'
            })
        }else{
            res.send({
                success:false,
                msg:'失败'
            })
        }
    })
})
module.exports=goods